package ru.spbau.bytecode.projectobserver;

import java.io.File;
import java.io.IOException;

import ru.spbau.bytecode.graph.Graph;
import ru.spbau.bytecode.graph.GraphBuilder;
import ru.spbau.bytecode.graph.GraphException;

public abstract class ProjectObserver implements GraphBuilder {

	protected void processDirectory(File directory,
			File projectDirectory, Graph graph) throws IOException {
		File classFilesOnly[] = directory.listFiles(new java.io.FileFilter() {
			public boolean accept(File pathname) {
				return pathname.isFile()
						&& pathname.getName().endsWith(".class");
			}
		});
		File directoriesOnly[] = directory.listFiles(new java.io.FileFilter() {
			public boolean accept(File pathname) {
				return pathname.isDirectory();
			}
		});

		if (classFilesOnly.length != 0) {
			findDependencies(classFilesOnly, projectDirectory, graph, directory);
		}

		for (File dir : directoriesOnly) {
			processDirectory(dir, projectDirectory, graph);
		}
	}
	
	@Override
	public Graph buildGraph(File projectDirectory) throws GraphException {
		Graph graph = new Graph();
		try {
			processDirectory(projectDirectory, projectDirectory, graph);
		} catch (IOException e) {
			throw new GraphException(e);
		}
		return graph;
	}

	
	protected abstract void findDependencies(File[] classFiles,
			File projectDirectory, Graph graph, File currentDirectory) throws IOException;
}
